<template>
  <div class="svg-gallery">
    <!-- 头部区域 -->
    <div class="gallery-header">
      <h1>SVG Gallery</h1>
      <p>A curated collection of beautiful SVG illustrations</p>
    </div>

    <!-- 上传区域 -->
    <div class="upload-section" v-if="!hasFiles">
      <div 
        class="upload-area"
        :class="{ 'drag-over': isDragOver }"
        @dragover.prevent="handleDragOver"
        @dragleave.prevent="handleDragLeave"
        @drop.prevent="handleDrop"
        @click="triggerFileInput"
      >
        <input 
          ref="fileInput"
          type="file"
          multiple
          accept=".svg"
          @change="handleFileSelect"
          style="display: none"
        />
        <div class="upload-content">
          <div class="upload-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <polyline points="17,8 12,3 7,8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <line x1="12" y1="3" x2="12" y2="15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            </svg>
          </div>
          <h3>Upload SVG Files</h3>
          <p>Drag and drop your SVG files here, or click to browse</p>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar" v-if="hasFiles">
      <div class="toolbar-left">
        <button class="upload-btn" @click="triggerFileInput">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="currentColor" stroke-width="2"/>
            <polyline points="17,8 12,3 7,8" stroke="currentColor" stroke-width="2"/>
            <line x1="12" y1="3" x2="12" y2="15" stroke="currentColor" stroke-width="2"/>
          </svg>
          Upload More
        </button>
        <button class="preview-btn" @click="goToPreview">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" stroke="currentColor" stroke-width="2"/>
            <circle cx="12" cy="12" r="3" stroke="currentColor" stroke-width="2"/>
          </svg>
          Preview Mode
        </button>
        <button class="refresh-btn" @click="refreshGallery">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <polyline points="23,4 23,10 17,10" stroke="currentColor" stroke-width="2"/>
            <polyline points="1,20 1,14 7,14" stroke="currentColor" stroke-width="2"/>
            <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke="currentColor" stroke-width="2"/>
          </svg>
          Refresh
        </button>
        <input 
          ref="fileInput"
          type="file"
          multiple
          accept=".svg"
          @change="handleFileSelect"
          style="display: none"
        />
      </div>
      <div class="toolbar-right">
        <div class="gallery-stats" v-if="hasFiles">
          <span class="stat-item">
            总计：{{ svgFiles.length }}
          </span>
          <span class="stat-item custom" v-if="customCreatedCount > 0">
            ✨ 自创：{{ customCreatedCount }}
          </span>
        </div>
        <div class="search-container">
          <input 
            type="text" 
            v-model="searchQuery"
            placeholder="Search SVGs..."
            class="search-input"
          />
        </div>
        <select v-model="sortBy" class="sort-select">
          <option value="name">Sort by Name</option>
          <option value="date">Sort by Date</option>
          <option value="size">Sort by Size</option>
        </select>
      </div>
    </div>

    <!-- SVG 卡片网格 -->
    <div class="gallery-grid" v-if="hasFiles">
      <SvgCard 
        v-for="svg in filteredSvgFiles"
        :key="svg.id"
        :svg="svg"
        @toggle-favorite="toggleFavorite"
        @download="downloadSvg"
        @preview="openPreview"
      />
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-if="hasFiles && filteredSvgFiles.length === 0">
      <div class="empty-icon">
        <svg width="64" height="64" viewBox="0 0 24 24" fill="none">
          <circle cx="11" cy="11" r="8" stroke="currentColor" stroke-width="2"/>
          <path d="m21 21-4.35-4.35" stroke="currentColor" stroke-width="2"/>
        </svg>
      </div>
      <h3>No SVGs found</h3>
      <p>Try adjusting your search terms</p>
    </div>

    <!-- 预览模态框 -->
    <div class="preview-modal" v-if="selectedSvg" @click="closePreview">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ selectedSvg.displayName }}</h3>
          <button @click="closePreview" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <div class="large-preview" v-html="selectedSvg.content"></div>
        </div>
        <div class="modal-actions">
          <button @click="downloadSvg(selectedSvg)" class="modal-btn primary">Download</button>
          <button @click="copySvg(selectedSvg)" class="modal-btn secondary">Copy Code</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import SvgCard from './SvgCard.vue'

const router = useRouter()

const goToPreview = () => {
  router.push('/preview')
}

const refreshGallery = () => {
  loadSvgFiles()
  alert('图库已刷新！')
}

// 响应式数据
const svgFiles = ref([])
const isDragOver = ref(false)
const searchQuery = ref('')
const sortBy = ref('name')
const selectedSvg = ref(null)
const fileInput = ref(null)

// 示例数据
const sampleSvgs = [
  {
    id: 1,
    name: "abstract-waves.svg",
    displayName: "Abstract Waves",
    category: "Abstract",
    description: "Flowing wave pattern with gradient colors",
    tags: ["waves", "abstract", "gradient"],
    isFavorited: false,
    content: `<svg width="300" height="200" viewBox="0 0 300 200" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="waveGradient" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
          <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
        </linearGradient>
      </defs>
      <path d="M0,100 Q75,50 150,100 T300,100 L300,200 L0,200 Z" fill="url(#waveGradient)"/>
    </svg>`,
    size: 1024,
    uploadDate: new Date()
  },
  {
    id: 2,
    name: "geometric-mountains.svg",
    displayName: "Geometric Mountains",
    category: "Nature",
    description: "Minimalist mountain landscape with geometric shapes",
    tags: ["mountains", "geometric", "landscape"],
    isFavorited: false,
    content: `<svg width="300" height="200" viewBox="0 0 300 200" xmlns="http://www.w3.org/2000/svg">
      <polygon points="50,150 100,80 150,150" fill="#ff9a9e" opacity="0.8"/>
      <polygon points="120,150 180,60 240,150" fill="#a8e6cf" opacity="0.8"/>
      <polygon points="200,150 250,90 300,150" fill="#ffd3a5" opacity="0.6"/>
      <circle cx="240" cy="50" r="25" fill="#ffd700" opacity="0.7"/>
    </svg>`,
    size: 856,
    uploadDate: new Date()
  },
  {
    id: 3,
    name: "floral-pattern.svg",
    displayName: "Floral Pattern",
    category: "Nature",
    description: "Elegant floral design with organic curves",
    tags: ["floral", "pattern", "organic"],
    isFavorited: false,
    content: `<svg width="300" height="200" viewBox="0 0 300 200" xmlns="http://www.w3.org/2000/svg">
      <g transform="translate(150,100)">
        <circle cx="0" cy="0" r="15" fill="#ff6b6b"/>
        <circle cx="20" cy="-10" r="12" fill="#4ecdc4"/>
        <circle cx="-15" cy="18" r="10" fill="#45b7d1"/>
        <circle cx="10" cy="20" r="14" fill="#96ceb4"/>
        <circle cx="-20" cy="-8" r="11" fill="#feca57"/>
        <circle cx="0" cy="-25" r="9" fill="#ff9ff3"/>
      </g>
    </svg>`,
    size: 692,
    uploadDate: new Date()
  }
]

// 计算属性
const hasFiles = computed(() => svgFiles.value.length > 0)

const customCreatedCount = computed(() => 
  svgFiles.value.filter(svg => svg.category === 'Custom').length
)

const filteredSvgFiles = computed(() => {
  const query = searchQuery.value?.toLowerCase() || ''
  
  let filtered = svgFiles.value.filter(svg => {
    const displayName = svg.displayName?.toLowerCase() || ''
    const category = svg.category?.toLowerCase() || ''
    const tags = svg.tags || []
    
    return displayName.includes(query) ||
           category.includes(query) ||
           tags.some(tag => tag?.toLowerCase().includes(query))
  })
  
  // 排序
  filtered.sort((a, b) => {
    switch (sortBy.value) {
      case 'name':
        return (a.displayName || '').localeCompare(b.displayName || '')
      case 'size':
        return (b.size || 0) - (a.size || 0)
      case 'date':
        return new Date(b.uploadDate || 0) - new Date(a.uploadDate || 0)
      default:
        return 0
    }
  })
  
  return filtered
})

// 方法
const triggerFileInput = () => {
  fileInput.value.click()
}

const handleDragOver = (e) => {
  isDragOver.value = true
}

const handleDragLeave = (e) => {
  isDragOver.value = false
}

const handleDrop = (e) => {
  isDragOver.value = false
  const files = Array.from(e.dataTransfer.files)
  processFiles(files)
}

const handleFileSelect = (e) => {
  const files = Array.from(e.target.files)
  processFiles(files)
}

const processFiles = (files) => {
  files.forEach(file => {
    if (file.type === 'image/svg+xml' || file.name.endsWith('.svg')) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const svgContent = e.target.result
        const svgFile = {
          id: Date.now() + Math.random(),
          name: file.name,
          displayName: file.name.replace('.svg', '').replace(/[-_]/g, ' '),
          category: 'Custom',
          description: 'Custom uploaded SVG',
          tags: ['custom', 'uploaded'],
          content: svgContent,
          size: file.size,
          isFavorited: false,
          uploadDate: new Date()
        }
        svgFiles.value.push(svgFile)
        saveSvgFiles()
      }
      reader.readAsText(file)
    }
  })
}

const toggleFavorite = (svg) => {
  svg.isFavorited = !svg.isFavorited
  saveSvgFiles()
}

const downloadSvg = (svg) => {
  const blob = new Blob([svg.content], { type: 'image/svg+xml' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = svg.name
  a.click()
  URL.revokeObjectURL(url)
}

const copySvg = (svg) => {
  navigator.clipboard.writeText(svg.content).then(() => {
    alert('SVG code copied to clipboard!')
  })
}

const openPreview = (svg) => {
  selectedSvg.value = svg
}

const closePreview = () => {
  selectedSvg.value = null
}

const saveSvgFiles = () => {
  localStorage.setItem('svgGalleryFiles', JSON.stringify(svgFiles.value))
}

const loadSvgFiles = () => {
  const saved = localStorage.getItem('svgGalleryFiles')
  if (saved) {
    svgFiles.value = JSON.parse(saved)
  } else {
    // 如果没有保存的文件，使用示例数据
    svgFiles.value = [...sampleSvgs]
  }
}

// 生命周期
onMounted(() => {
  loadSvgFiles()
  
  // 监听 localStorage 变化（当从其他页面保存 SVG 时自动刷新）
  window.addEventListener('storage', handleStorageChange)
  
  // 监听自定义事件（同一标签页内的更新）
  window.addEventListener('svgGalleryUpdated', handleGalleryUpdate)
})

// 清理事件监听器
onUnmounted(() => {
  window.removeEventListener('storage', handleStorageChange)
  window.removeEventListener('svgGalleryUpdated', handleGalleryUpdate)
})

const handleStorageChange = (e) => {
  if (e.key === 'svgGalleryFiles') {
    loadSvgFiles()
  }
}

const handleGalleryUpdate = () => {
  loadSvgFiles()
}
</script>

<style scoped>
.svg-gallery {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.gallery-header {
  text-align: center;
  margin-bottom: 60px;
}

.gallery-header h1 {
  font-size: 3rem;
  font-weight: 700;
  color: #667eea;
  margin-bottom: 12px;
  letter-spacing: -0.02em;
}

.gallery-header p {
  font-size: 1.2rem;
  color: #6b7280;
  font-weight: 400;
}

.upload-section {
  margin-bottom: 40px;
}

.upload-area {
  border: 2px dashed #d1d5db;
  border-radius: 16px;
  padding: 60px 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.upload-area:hover,
.upload-area.drag-over {
  border-color: #667eea;
  background: #f0f4ff;
}

.upload-content {
  max-width: 400px;
  margin: 0 auto;
}

.upload-icon {
  color: #9ca3af;
  margin-bottom: 20px;
}

.upload-content h3 {
  font-size: 1.5rem;
  color: #374151;
  margin-bottom: 8px;
  font-weight: 600;
}

.upload-content p {
  color: #6b7280;
  font-size: 1rem;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  padding: 0 4px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.upload-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.upload-btn:hover {
  background: #5a67d8;
  transform: translateY(-1px);
}

.preview-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: #10b981;
  color: white;
  border: none;
  border-radius: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.preview-btn:hover {
  background: #059669;
  transform: translateY(-1px);
}

.refresh-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: #f59e0b;
  color: white;
  border: none;
  border-radius: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.refresh-btn:hover {
  background: #d97706;
  transform: translateY(-1px);
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.gallery-stats {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px 16px;
  background: #f3f4f6;
  border-radius: 8px;
  font-size: 0.85rem;
}

.stat-item {
  color: #6b7280;
  font-weight: 500;
}

.stat-item.custom {
  color: #10b981;
  font-weight: 600;
}

.search-container {
  position: relative;
}

.search-input {
  width: 250px;
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 10px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.search-input:focus {
  border-color: #667eea;
}

.sort-select {
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 10px;
  font-size: 14px;
  outline: none;
  cursor: pointer;
  background: white;
}

.gallery-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 32px;
}



.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #9ca3af;
}

.empty-icon {
  margin-bottom: 20px;
}

.empty-state h3 {
  font-size: 1.5rem;
  margin-bottom: 8px;
  color: #6b7280;
}

.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 20px;
  max-width: 600px;
  width: 90%;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid #f3f4f6;
}

.modal-header h3 {
  margin: 0;
  color: #111827;
  font-size: 1.5rem;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6b7280;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: #f3f4f6;
}

.modal-body {
  flex: 1;
  padding: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: auto;
}

.large-preview {
  max-width: 100%;
  max-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.large-preview svg {
  max-width: 100%;
  max-height: 400px;
  width: auto;
  height: auto;
}

.modal-actions {
  display: flex;
  gap: 12px;
  padding: 24px;
  border-top: 1px solid #f3f4f6;
  justify-content: flex-end;
}

.modal-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.modal-btn.primary {
  background: #667eea;
  color: white;
}

.modal-btn.primary:hover {
  background: #5a67d8;
}

.modal-btn.secondary {
  background: #f3f4f6;
  color: #374151;
}

.modal-btn.secondary:hover {
  background: #e5e7eb;
}

@media (max-width: 768px) {
  .gallery-header h1 {
    font-size: 2.5rem;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .toolbar-right {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .gallery-stats {
    order: -1;
    justify-content: center;
  }
  
  .search-input {
    width: 100%;
  }
  
  .gallery-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .svg-gallery {
    padding: 20px 16px;
  }
  
  .gallery-header h1 {
    font-size: 2rem;
  }
  
  .search-input {
    width: 160px;
  }
}
</style> 